package com.spark.colliery.module.message

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.annotation.LayoutRes
import android.support.v7.widget.LinearLayoutManager
import android.text.Html
import android.view.View
import android.widget.ImageView
import com.blankj.utilcode.util.LogUtils
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.spark.colliery.MainFragment
import com.spark.colliery.R
import com.spark.check.StdCheckNotifyFragment
import com.spark.common.BaseFragment
import com.spark.common.Const
import com.spark.common.ext.*
import com.spark.common.helper.BottomSheet
import com.spark.common.model.MessageListModel
import com.spark.common.net.Http
import com.spark.common.net.toJsonBody
import com.spark.data.BorrowApplyResultNotifyFragment
import com.spark.data.FileTransferNotifyFragment
import com.spark.trouble.TroubleDealFragment
import com.spark.trouble.handle.HTinputActivity
import kotlinx.android.synthetic.main.fragment_message.*
import me.yokeyword.fragmentation.SupportFragment

/**
 * 消息首页
 */

class MessageHomeFragment : BaseFragment() {
    var categoryList = mutableListOf("全部", "日常办公", "纠违处理", "标化工作", "标化检查", "隐患排查", "培训学习")
    private lateinit var messageListAdapter: MessageListAdapter
    private var currPage = 1
    private var totalPage = 1

    companion object {
        fun newInstance(): MessageHomeFragment {
            val fragment = MessageHomeFragment()
            return fragment
        }
    }

    override fun contentResId(): Int {
        return R.layout.fragment_message
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // 分类按钮
        ll_category.setOnClickListener { v ->
            activity?.apply {
                BottomSheet.show(this, categoryList) { adapter, _, position ->
                    currPage = 1
                    fetchMessageList(page = currPage, messageType = position)
                }
            }
        }

        messageListAdapter = MessageListAdapter(R.layout.item_message).also {
            it.setOnItemClickListener { _, _, position ->
                val data = messageListAdapter.data[position]
                when (data.id) {
                    // common chat
                    1 -> {
                    }
                    // 标准化检查
                    2 -> {
                        parentFragment?.let { it as MainFragment }?.start(StdCheckNotifyFragment.newInstance())
                    }
                    // 借阅申请
                    3 -> {
                        parentFragment?.let { it as SupportFragment }?.start(BorrowApplyResultNotifyFragment.newInstance("389", "3"))
                    }
                    // 文件传输
                    4 -> {
                        parentFragment?.let { it as SupportFragment }?.start(FileTransferNotifyFragment.newInstance("430", "4"))
                    }
                    // 纠违处理
                    5 -> {
                    }
                    // 隐患处理
                    6 -> {
                        parentFragment?.let { it as SupportFragment }?.start(TroubleDealFragment.newInstance())
                    }
                    // 隐患录入
                    7 -> {
                        activity?.apply { HTinputActivity.actionStart(this) }
                    }
                }
            }
        }
        recy_msgs.apply {
            adapter = messageListAdapter
            layoutManager = LinearLayoutManager(context)
        }

        fetchMessageList(currPage)
        refresh_layout.apply {
            setOnLoadmoreListener {
                if (currPage >= totalPage) {
                    alert("没有更多数据了")
                    refresh_layout.finishRefresh()
                } else {
                    currPage++
                    fetchMessageList(currPage)
                }
            }
            setOnRefreshListener {
                currPage = 1
                fetchMessageList(currPage)
            }
        }
    }

    @SuppressLint("CheckResult")
    private fun fetchMessageList(page: Int, messageType: Int = -1) {
        // messageType : 消息类型
        val params = mutableMapOf(
                Const.qr_pageNum to "$page",
                Const.qr_pageSize to "10"
        )
        if (messageType != -1)
            params["messageType"] = "$messageType"
        Http.request()
                .rxPost("${Const.base_url}${Const.act_message_list}", params.toJsonBody())
                .wrapIO()
                .subscribe(
                        {
                            LogUtils.e(it)
                            Gson().fromJson(it, MessageListModel::class.java)?.apply {
                                if (code == "200") {
                                    totalPage = data.pageCount
                                    if (page == 1) {
                                        messageListAdapter.data.clear()
                                    }
                                    messageListAdapter.addData(resultMaps)
                                }
                            }
                        },
                        {
                            it.printStackTrace()
                            report(it)
                            if (page == 1) refresh_layout.finishRefresh() else refresh_layout.finishLoadmore()
                        },
                        {
                            if (page == 1) refresh_layout.finishRefresh() else refresh_layout.finishLoadmore()
                        },
                        {
                            dispose = it
                        }
                )
    }
}


class MessageListAdapter(@LayoutRes layoutRes: Int) : BaseQuickAdapter<MessageListModel.ResultMap, BaseViewHolder>(layoutRes) {
    private val sdf = sdf("yyy-MM-dd HH:mm:ss")
    override fun convert(helper: BaseViewHolder?, item: MessageListModel.ResultMap?) {
        helper?.apply {
            if (item == null) return
            setText(R.id.tv_time, sdf.format(item.send_time))
            setText(R.id.tv_title, item.title)
            setText(R.id.tv_desc, Html.fromHtml(item.content))
            getView<ImageView>(R.id.iv_avatar).setImageResource(R.drawable.btn_home_options_meeting)
        }
    }

}
